package cn.lentme.demo.ui.main

import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import cn.lentme.demo.R
import cn.lentme.demo.databinding.ActivityMainBinding
import cn.lentme.demo.request.viewmodel.MainViewModel
import cn.lentme.demo.base.BaseActivity
import cn.lentme.demo.fragments.blank.BlankFragment
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() {

    override fun fetchBinding() = ActivityMainBinding.inflate(layoutInflater)
    override fun fetchViewModel(): MainViewModel = getViewModel()

    private val fragments = listOf(BlankFragment(), BlankFragment(), BlankFragment())

    override fun initUI() {
        super.initUI()
        mBinding.mainViewpager.adapter = fragmentStateAdapter
        mBinding.mainViewpager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mBinding.mainNav.menu.getItem(position).isChecked = true
            }
        })
        mBinding.mainNav.setOnItemSelectedListener {
            var index = 0
            when(it.itemId) {
                R.id.nav_1 -> index = 0
                R.id.nav_2 -> index = 1
                R.id.nav_3 -> index = 2
            }
            mBinding.mainViewpager.currentItem = index
            false
        }
    }

    private val fragmentStateAdapter by lazy {
        object :FragmentStateAdapter(this) {
            override fun getItemCount() = fragments.size
            override fun createFragment(position: Int) = fragments[position]
        }
    }
}